import platformApi from "./utils/platform";
import ErrorTypes from './utils/errorTypes';

/**
 * 蓝牙连接功能模块
 * @param {Object} config - 配置项对象
 * @param {function} config.errorHandler - 异常处理函数
 * @returns {Object} - 包含初始化蓝牙方法的对象
 */
export default function (config) {
  const { errorHandler } = config;

  /**
   * 检查蓝牙权限
   * @returns {Promise} - 权限检查结果的 Promise
   */
  const checkPermissions = () =>
    new Promise((resolve, reject) => {
      platformApi.getSetting({
        success: ({ authSetting }) => {
          if (authSetting["scope.bluetooth"] === true) return resolve();

          platformApi.authorize({
            scope: "scope.bluetooth",
            success: resolve,
            fail: () => {
              platformApi.showModal({
                title: "权限要求",
                content: "需要蓝牙权限以连接设备",
                success: ({ confirm }) =>
                  confirm ? platformApi.openSetting() : reject(),
              });
            },
          });
        },
        fail: reject,
      });
    });

  /**
   * 初始化蓝牙适配器
   * @returns {Promise} - 初始化结果的 Promise
   */
  const initBluetoothAdapter = () => {
    return new Promise((resolve, reject) => {
      platformApi.openBluetoothAdapter({
        success: () => {
          setupBluetoothAdapterListeners();
          resolve();
        },
        fail: (err) => {
          if (err.errMsg === "openBluetoothAdapter:fail already opened") {
            setupBluetoothAdapterListeners();
            resolve();
          } else {
            reject(err);
          }
        },
      });
    });
  };

  /**
   * 设置蓝牙适配器监听
   */
  const setupBluetoothAdapterListeners = () => {
    // 监听蓝牙适配器状态变化
    platformApi.onBluetoothAdapterStateChange((state) => {
      console.log("蓝牙适配器状态变化:", state);
      if (!state.available) {
        errorHandler(ErrorTypes.BLUETOOTH_CONNECTION_FAILED, "蓝牙已断开", new Error("蓝牙已断开"));
      }
    });
  };

  /**
   * 初始化蓝牙
   * @returns {Promise} - 初始化结果的 Promise
   */
  const initBluetooth = () => {
    return new Promise(async (resolve) => {
      try {
        await checkPermissions();
        console.log("蓝牙已授权");
        await initBluetoothAdapter();
        console.log("蓝牙已初始化完成");
        resolve(true);
      } catch (error) {
        resolve(false);
        const errorMap = {
          10000: "蓝牙未初始化",
          10001: "蓝牙不可用，请检查手机蓝牙设置",
          10002: "未找到指定设备",
          10003: "连接失败，请重试",
          10004: "未找到指定服务",
          10005: "未找到指定特征值",
          10006: "连接已断开",
          10007: "当前操作不支持",
          10008: "系统蓝牙异常",
          10009: "您的手机系统版本过低（需Android 4.3+）",
          10012: "连接超时",
          10013: "设备ID无效",
        };

        const message =
          errorMap[err?.errCode || ""] || err.message || "蓝牙连接失败";

        errorHandler(ErrorTypes.BLUETOOTH_CONNECTION_FAILED, message, error);
      }
    });
  };

  /**
   * 断开蓝牙适配器
   * @returns {Promise} - 断开结果的 Promise
   */
  const disconnectBluetoothAdapter = () => {
    return new Promise((resolve, reject) => {
      platformApi.closeBluetoothAdapter({
        success: () => {
          console.log("蓝牙适配器已断开");
          resolve();
        },
        fail: (err) => {
          reject(new Error(`断开蓝牙适配器失败: ${err.errMsg}`));
        },
      });
    });
  };

  return { initBluetooth, disconnectBluetoothAdapter };
}
